Strategy Pattern
1 min readRapid overview
Strategy Pattern — Switching behavior at runtime
Encapsulate algorithms behind a shared interface so you can swap behavior without branching logic.
Example (TypeScript)
type PricingStrategy = (base: number) => number;
const standard: PricingStrategy = (base) => base;
const discounted = (pct: number): PricingStrategy => (base) => base * (1 - pct);
const quote = (base: number, strategy: PricingStrategy) => strategy(base);
quote(100, standard);
quote(100, discounted(0.2));
Why it matters
- Avoids
if/elsetrees for feature variants. - Encourages testable, focused behavior units.
- Lets you inject behavior based on config or runtime data.
Questions & Answers
Q: When do you apply Strategy?
A: When behavior changes by feature flag, locale, pricing tier, or runtime input and you want to avoid branching logic.
Q: How do you select a strategy?
A: Use a factory or lookup map keyed by config, user segment, or request metadata.
Q: Strategy vs State?
A: Strategy swaps behavior per call; State models transitions over time.